<?php
//======================================================
// Copyright (C) 2004 John W. Holmes, All Rights Reserved
//
// This file is part of the Unit Command Climate
// Assessment and Survey System (UCCASS)
//
// UCCASS is free software; you can redistribute it and/or
// modify it under the terms of the Affero General Public License as
// published by Affero, Inc.; either version 1 of the License, or
// (at your option) any later version.
//
// http://www.affero.org/oagpl.html
//
// UCCASS is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// Affero General Public License for more details.
//======================================================

//Constants for different edit survey sections
define('MODE_PROPERTIES','properties');
define('MODE_EDITQUESTION','edit_question');
define('MODE_QUESTIONS','questions');
define('MODE_NEWQUESTION','new_question');
define('MODE_ACCESSCONTROL','access_control');

//Constant for moving questions up or down
//in question list
define('MOVE_UP',1);
define('MOVE_DOWN',2);

//Survey Limits
define('SL_MINUTES',0);
define('SL_HOURS',1);
define('SL_DAYS',2);
define('SL_EVER',3);

//User Status
define('USERSTATUS_NONE',0);
define('USERSTATUS_INVITEE',1);
define('USERSTATUS_INVITED',2);
define('USERSTATUS_SENTLOGIN',3);

//String to seperate headers from
//body in email templates
define('HEADER_SEPERATOR','<!-- HEADER SEPERATOR - DO NOT REMOVE -->');

//Invitation code types
define('INVITECODE_ALPHANUMERIC','alphanumeric');
define('INVITECODE_WORDS','words');
define('ALPHANUMERIC_MAXLENGTH',20);
define('ALPHANUMERIC_DEFAULTLENGTH',10);
define('WORDCODE_SEPERATOR','-');
define('WORDCODE_NUMWORDS',2);

class UCCASS_EditSurvey extends UCCASS_Main
{
    //Load configuration and initialize data variable
    function UCCASS_EditSurvey()
    {
        $this->load_configuration();
        $this->data = array();
    }

    //Show edit survey page based upon request variables
    function show($sid)
    {
        
		$sid = (int)$sid;
		$qid = (int)$qid;
        $retval = '';
 
        //Ensure user is logged in with valid privileges
        //for the requested survey or is an administrator
        if(!$this->_CheckLogin($sid,EDIT_PRIV,"question_edit_survey.php?sid=$sid"))
        { return $this->showLogin('question_edit_survey.php',array('sid'=>$sid)); }

       //Show links at top of page
        $this->data['show']['links'] = TRUE;
        $this->data['content'] = MODE_PROPERTIES;
        $this->data['mode'] = MODE_PROPERTIES;
        $this->data['sid'] = $sid;
 

       //Set default mode if not present
        /*if(!isset($_REQUEST['mode']))
        { $_REQUEST['mode'] = MODE_PROPERTIES; }*/

        $qid = (int)@$_REQUEST['qid'];
        
        
        /****************saber que tipo de encuesta es**********************/
        $query = "SELECT tipo  
                  FROM {$this->CONF['db_tbl_prefix']}surveys 
                  WHERE sid = $sid";
        
        $rs = $this->db->Execute($query);
		
		if($rs === FALSE)
        { $this->error("Error obteniendo tipo de encuesta: " . $this->db->ErrorMsg()); return; }
        
        if($r = $rs->FetchRow($rs))
        {
          $this->data['tipo'] = $r['tipo'];
        }
        
        /*******************************************************************/

         switch($_REQUEST['mode'])
        {
			//Methods that handle the display and processing
            //of the question list
            // - Add new question
            // - Processing editing of question
            // - Showing question list
			
            case MODE_QUESTIONS:
			
                if(isset($_REQUEST['add_new_question']))
                { $this->_processAddQuestion($sid); }
                elseif(isset($_REQUEST['edit_question_submit']))
                { $this->_processEditQuestion($sid,$qid); }
                else
                {
                    $this->data['content'] = MODE_QUESTIONS;
                    $this->_loadQuestions($sid);
                }
            break;

         }
		
        $this->smarty->assign_by_ref('data',$this->data);
				
        //Retrieve template that shows links for edit survey page
        $this->data['links'] = ($this->data['show']['links']) ? $this->smarty->Fetch($this->template.'/edit_survey_links.tpl') : '';
        
        
        if(isset($this->data['content']))
        {$this->data['content'] = $this->smarty->Fetch($this->template.'/edit_survey_' . $this->data['content'] . '.tpl');	}

        //Retrieve entire edit surey page based upon the content set above
        return $this->smarty->Fetch($this->template.'/add_survey_questions.tpl');

    }

	// DELETE ANSWERS/RESULTS FROM SURVEY //
    /*function _processDeleteAnswers($sid)
    {
        $sid = (int)$sid;
        $error = array();

        //set tables to delete any results from to clear all answers from this survey
        $tables = array('results','results_text','ip_track','time_limit');
        foreach($tables as $tbl)
        {
            $rs = $this->db->Execute("DELETE FROM {$this->CONF['db_tbl_prefix']}$tbl WHERE sid = $sid");
            if($rs === FALSE)
            { $error[] = 'Unable to delete results from ' . $tbl . ': ' . $this->db->ErrorMsg(); }
        }

        $this->setMessageRedirect("add_answer.php?sid=$sid&mode=properties");

        if(empty($error))
        {
            //Set error message and redirect back to properties page
            $this->setMessage('Clear Answers Error',implode('<br />',$error),MSGTYPE_ERROR);
        }
        else
        {
            //Set success message and redirect back to properties page
            $this->setMessage('Success','All answers cleared from survey',MSGTYPE_NOTICE);
        }
    }*/

    // REMOVE DEPENDENCIES //
    function _processDeleteDependency($sid,$dep_id)
    {
        $error = array();

        //Loop through and delete any dependency IDs that are passed
        if(is_array($dep_id) && !empty($dep_id))
        {
            $id_list = '';
            foreach($dep_id as $id)
            { $id_list .= 'dep_id = ' . (int)$id . ' OR '; }
            $id_list = substr($id_list,0,-3);

            $query = "DELETE FROM {$this->CONF['db_tbl_prefix']}dependencies WHERE sid = $sid AND ($id_list)";
            $rs = $this->db->Execute($query);
            if($rs === FALSE)
            { $rror[] = 'Error deleting dependencies: ' . $this->db->ErrorMsg(); }
        }

        return $error;
    }

    // ADD DEPENDENCY TO QUESTION //
    function _processAddDependency($sid,$qid)
    {
        $error = array();
        $dep = $this->_validateDependency($sid,$qid);

        //Loop through any new dependencies passed from form. If dependency is based upon
        //a question on the same page, force the creation of a page break.
        if(empty($dep['error']) && !empty($dep['input']))
        {
            foreach($dep['input']['dep_aid'] as $num=>$dep_aid_array)
            {
                foreach($dep_aid_array as $dep_aid)
                {
                    $dep_insert = '';
                    $dep_id = $this->db->GenID($this->CONF['db_tbl_prefix'].'dependencies_sequence');
                    $dep_insert = "($dep_id,$sid,$qid,{$dep['input']['dep_qid'][$num]},{$dep_aid},{$dep['input']['option'][$num]})";

                    $query = "INSERT INTO {$this->CONF['db_tbl_prefix']}dependencies (dep_id, sid, qid, dep_qid, dep_aid, dep_option)
                            VALUES " . $dep_insert;
                    $rs = $this->db->Execute($query);
                    if($rs === FALSE)
                    { $error[] = 'Error inserting dependencies: ' . $this->db->ErrorMsg(); }
                }
            }

            if(isset($dep['input']['dep_require_pagebreak']))
            {
                $query = "UPDATE {$this->CONF['db_tbl_prefix']}questions SET page = page + 1 WHERE sid = $sid AND
                        (page > {$dep['input']['page']} OR (page = {$dep['input']['page']} AND oid > {$dep['input']['oid']}) OR qid = $qid)";
                $rs = $this->db->Execute($query);
                if($rs === FALSE)
                { $error[] = 'Cannot insert dependency page break: ' . $this->db->ErrorMsg(); }
            }
        }
        return array_merge($error,$dep['error']);
    }

    // VALIDATE NEW DEPENDENCIES //
    function _validateDependency($sid,$qid)
    {
        $input = array();
        $error = array();

        if(isset($_REQUEST['option']) && is_array($_REQUEST['option']) && !empty($_REQUEST['option']))
        {
            foreach($_REQUEST['option'] as $num=>$option)
            {
                if(!empty($option))
                {
                    //Valide dependency option chosen (hide, require or show)
                    if(empty($option) || !in_array($option,$this->CONF['dependency_modes']))
                    { $error[] = 'Please choose a valid option (hide, show, etc)'; }
                    else
                    { $input['option'][$num] = $this->SfStr->getSafeString($option,SAFE_STRING_DB); }

                    //Validate question ID to add depenency to
                    if(empty($_REQUEST['dep_qid'][$num]))
                    { $error[] = 'Please choose a question to add dependency to.'; }
                    else
                    { $input['dep_qid'][$num] = (int)$_REQUEST['dep_qid'][$num]; }

                    //Validate question ID to base dependency on
                    if(empty($_REQUEST['dep_aid'][$num]))
                    { $error[] = 'Please choose a question to base the new dependency on.'; }
                    else
                    {
                        foreach($_REQUEST['dep_aid'][$num] as $dep_aid)
                        { $input['dep_aid'][$num][] = (int)$dep_aid; }
                    }

                    $input['dep_qid'][$num] = (int)$_REQUEST['dep_qid'][$num];

                    //Ensure question chosen to base new dependency on is before the question the dependency
                    //is being added to. If both are on the same page, set a flag to require a page break
                    //be added before the selected question.
                    $check_query = "SELECT q1.page, q1.oid, q2.page AS dep_page, q2.oid AS dep_oid
                                    FROM {$this->CONF['db_tbl_prefix']}questions q1, {$this->CONF['db_tbl_prefix']}questions q2
                                    WHERE q1.qid = $qid AND q2.qid = {$input['dep_qid'][$num]}";

                    $rs = $this->db->Execute($check_query);
                    if($rs === FALSE)
                    { $error[] = 'Error checking page break requirement for dependency: ' . $this->db->ErrorMsg(); }

                    while($r = $rs->FetchRow($rs))
                    {
                        if($r['dep_page'] > $r['page'] || ($r['dep_page'] == $r['page'] && $r['dep_oid'] > $r['oid']))
                        { $error[] = 'Error: Dependencies can only be based on questions displayed BEFORE the question being added'; }
                        elseif($r['page'] == $r['dep_page'])
                        {
                            $input['dep_require_pagebreak'] = 1;
                            $input['page'] = $r['page'];
                            $input['oid'] = $r['oid'];
                        }
                    }
                }
            }
        }
        return(array('input'=>$input, 'error'=>$error));
    }
   
   // LOAD EXISTING QUESTIONS FOR SURVEY //
    function _loadQuestions($sid)
    {  
        $sid = (int)$sid;
        $this->data['mode_edit_question'] = MODE_EDITQUESTION;
        $this->data['mode_new_question'] = MODE_QUESTIONS;

        $this->data['sid'] = $sid;
        
        
        
        
        //load all questions for this survey
        $query = "SELECT q.qid, q.aid, q.question, q.page, q.oid, s.survey_text_mode 
                  FROM {$this->CONF['db_tbl_prefix']}questions q,
                  {$this->CONF['db_tbl_prefix']}surveys s
                  WHERE q.sid = $sid AND q.sid = s.sid order by q.page, q.oid";
       
       
        $rs = $this->db->Execute($query);
		//echo $query;
		if($rs === FALSE)
        { $this->error("Error selecting questions: " . $this->db->ErrorMsg()); return; }
        $page = 1;
        $x = 0;
        $q_num = 1;
        $label_num = 1;
        $num_demographics = 0;
        $this->data['answer'] = array();
        $this->data['show']['dep'] = TRUE;

        if($r = $rs->FetchRow($rs))
        {
            $survey_text_mode = $r['survey_text_mode'];
            do
            {
                //Load data for each question into the $data array
                while($page != $r['page'])
                {   
                    $this->data['qid'][$x] = $r['page'];
					$this->data['aid'][$x] = $r['aid'];					
                    $this->data['question'][$x] = $this->CONF['page_break'];
                    $this->data['qnum'][$x] = '&nbsp;';
                    $this->data['page_break'][$x] = TRUE;
                    $this->data['show_dep'][$x] = FALSE;
                    $x++;
                    $page += 1;
                }
                
                $this->data['qid'][$x] = $r['qid'];
				$this->data['aid'][$x] = $r['aid'];
                $this->data['question'][$x] = nl2br($this->SfStr->getSafeString($r['question'],$survey_text_mode));
                
                
                if($r['type'] == 'MS' || $r['type'] == 'MM')
                {
                	
                    //Retrieve answer value in safe_text mode
                    //so they can be shown in dependency <select>
                    $temp = $this->get_answer_values($r['aid'],BY_AID,SAFE_STRING_TEXT);
                    $this->data['dep_avid'][$r['qid']] = $temp['avid'];
                    $this->data['dep_value'][$r['qid']] = $temp['value'];
                }

                if($r['type'] != 'N')
                {
                	
                    $this->data['qnum'][$x] = $q_num++;
                    $this->data['page_oid'][] = $r['page'] . '-' . $r['oid'];
                    $this->data['qnum2'][] = $this->data['qnum'][$x];
                    $this->data['qnum2_selected'][] = '';

                    if($r['type'] != 'S' && $r['type'] != 'T')
                    {
                        $this->data['dep_qid'][] = $r['qid'];
                        $this->data['dep_qnum'][] = $this->data['qnum'][$x];
                    }

                }
                else
                {
                	
                    $this->data['qnum'][$x] = 'L'.$label_num++;
                    $this->data['page_oid'][] = $r['page'] . '-' . $r['oid'];
                    $this->data['qnum2'][] = $this->data['qnum'][$x];
                    $this->data['qnum2_selected'][] = '';
                }

                $this->data['show_edep'][$x] = FALSE;

                $x++;

            }while($r = $rs->FetchRow($rs));
            

            //load dependencies for current survey
            $query = "SELECT d.qid, d.dep_qid, av.value, d.dep_option FROM {$this->CONF['db_tbl_prefix']}dependencies d,
                      {$this->CONF['db_tbl_prefix']}answer_values av WHERE d.dep_aid = av.avid AND d.sid = $sid";
            $rs = $this->db->Execute($query);
            if($rs === FALSE)
            { $this->error('Error selecting dependencies for survey: ' . $this->db->ErrorMsg()); return; }

            while($r = $rs->FetchRow($rs))
            {
                // __hide__ if question __xx__ is __a,b,c__
                $x = array_search($r['qid'],$this->data['qid']);
                $key = array_search($r['dep_qid'],$this->data['qid']);
                $qnum = $this->data['qnum'][$key];

                $this->data['show_edep'][$x] = TRUE;
                if(isset($this->data['edep_value'][$x]) && in_array($qnum,$this->data['edep_qnum'][$x]))
                {
                    $key2 = array_search($qnum,$this->data['edep_qnum'][$x]);

                    if($this->data['edep_option'][$x][$key2] == $r['dep_option'])
                    { $this->data['edep_value'][$x][$key2] .= ', ' . $this->SfStr->getSafeString($r['value'],$survey_text_mode); }
                    else
                    {
                        $this->data['edep_option'][$x][] = $this->SfStr->getSafeString($r['dep_option'],$survey_text_mode);
                        $this->data['edep_value'][$x][] = $this->SfStr->getSafeString($r['value'],$survey_text_mode);
                        $this->data['edep_qnum'][$x][] = $qnum;
                    }
                }
                else
                {
                    $this->data['edep_option'][$x][] = $this->SfStr->getSafeString($r['dep_option'],$survey_text_mode);
                    $this->data['edep_value'][$x][] = $this->SfStr->getSafeString($r['value'],$survey_text_mode);
                    $this->data['edep_qnum'][$x][] = $qnum;
                }
            }
        }
        else
        { $this->data['show']['dep'] = FALSE; }

        //Create javascript to fill <select> boxes when creating dependencies
        if(isset($this->data['dep_avid']) && count($this->data['dep_avid']))
        {
            $this->data['js'] = '';

            foreach($this->data['dep_avid'] as $qid=>$avid_array)
            {
                foreach($avid_array as $key=>$avid)
                {
                    $this->data['js'] .= "Answers['$qid,$key'] = '$avid';\n";
                    $value = addslashes($this->data['dep_value'][$qid][$key]);
                    $this->data['js'] .= "Values['$qid,$key'] = '$value';\n";
                }
                $c = count($avid_array);
                $this->data['js'] .= "Num_Answers['$qid'] = '$c';\n";
            }
        }

        //Set "insert question after..." select box to last element
        if(isset($this->data['qnum2_selected']))
        { $this->data['qnum2_selected'][count($this->data['qnum2_selected'])-1] = ' selected'; }

        $this->data['num_answers'] = array("1","2","3","4","5");
        $this->data['num_answers_selected'] = array_fill(0,5,"");
        $this->data['num_answers_selected'][$this->data['question_data']['num_answers']-1] = " selected";

        $this->data['num_required'] = array("0","1","2","3","4","5");
        $this->data['num_required_selected'] = array_fill(0,6,"");
        $this->data['num_required_selected'][$this->data['question_data']['num_required']] = " selected";

        //retrieve answer types from database
        $rs = $this->db->Execute("SELECT aid, name FROM {$this->CONF['db_tbl_prefix']}answer_types
                                  WHERE sid = $sid ORDER BY name ASC");
        if($rs === FALSE)
        { $this->error('Unable to retrieve answer types: ' . $this->db->ErrorMsg()); return; }
        while ($r = $rs->FetchRow($rs))
        {
            $r['name'] = $this->SfStr->getSafeString($r['name'],SAFE_STRING_TEXT);
            $this->data['answer'][] = $r;
        }

        if(isset($_SESSION['answer_orientation']))
        {
            $key = array_search($_SESSION['answer_orientation'],$this->CONF['orientation']);
            $this->data['orientation']['selected'][$key] = ' selected';
        }
    }

    // PROCESSING ADDITION OF NEW QUESTION //
    function _processAddQuestion($sid)
    {
	
		$sid = (int)$sid;
        $error = array();
        $notice = '';
		$img_path = '';
		
		//echo var_dump($_FILES);
		//exit;
		
        //Ensure new question is not blank
        if(strlen($_REQUEST['question']) == 0)
        { $error[] = 'No puede insertar una pregunta Vacia, agregue el texto de la pregunta en el area de texto.'; }
        else
        {   
            //Determine what question to insert new question after

            $x = explode('-',$_REQUEST['insert_after']);
            
            $page = (int)$x[0];
            $oid = (int)$x[1];

            if(strcasecmp($_REQUEST['question'],$this->CONF['page_break'])==0)
            {
                //Set error if there is an attempt to make a page break the first question in the survey
                if($page == 0 && $oid == 0)
                { $error[] = 'Cannot insert PAGE BREAK as first question. Please use the drop down to select what question to insert the page break after.'; }
                else
                {
                    $query = "UPDATE {$this->CONF['db_tbl_prefix']}questions SET page = page + 1 WHERE sid = $sid AND
                              (page > $page) OR (page = $page AND oid > $oid)";
                    $rs = $this->db->Execute($query);
                    if($rs === FALSE)
                    { $error[] = 'Cannot insert page break: ' . $this->db->ErrorMsg(); }
                    elseif($this->db->Affected_Rows() > 0)
                    { $notice = 'PAGE BREAK inserted successfully.'; }
                    else
                    { $error[] = 'Cannot insert PAGE BREAK as last question.'; }
                }
            }
            else
            {
                //Make sure "first" question is page 1, oid 1,
                //not page 0, oid 0.
                if($page == 0) { $page=1; }

                $query = "UPDATE {$this->CONF['db_tbl_prefix']}questions SET oid = oid + 1 WHERE sid = $sid AND page = $page AND
                          oid > $oid";
                $rs = $this->db->Execute($query);
                if($rs === FALSE)
                { $error[] = 'Error updating OID to insert question: ' . $this->db->ErrorMsg(); }

                //Increment oid, since new question is
                //inserted "after" what was chosen
                //Validate number of answers, number required and orientation for new question
                $oid++;
                $question = $this->SfStr->getSafeString($_REQUEST['question'],SAFE_STRING_DB);
                $num_answers = (int)$_REQUEST['num_answers'];
                $num_required = (int)$_REQUEST['num_required'];
                $aid = (int)$_REQUEST['answer'];

                if($num_required > $num_answers)
                { $error[] = 'Number of required answers cannot exceed the number of answers'; }

                if(in_array($_REQUEST['orientation'],$this->CONF['orientation']))
                { $orientation = $this->SfStr->getSafeString($_REQUEST['orientation'],SAFE_STRING_DB); }
                else
                { $orientation = $this->SfStr->getSafeString('Vertical',SAFE_STRING_DB); }

                $_SESSION['answer_orientation'] = $_REQUEST['orientation'];

                //If there is no error so far, attempt to process the requested dependencies
                if(empty($error))
                {

                    $dep_insert = '';
                    $dep_require_pagebreak = 0;

                    //check for dependencies
                    if(isset($_REQUEST['option']))
                    {
                        foreach($_REQUEST['option'] as $num=>$option)
                        {
                            if(!empty($option) && !empty($_REQUEST['dep_qid'][$num]) && !empty($_REQUEST['dep_aid'][$num])
                               && in_array($option,$this->CONF['dependency_modes']))
                            {
                                $dep_qid = (int)$_REQUEST['dep_qid'][$num];

                                //Ensure dependencies are based on questions before the question being added
                                $check_query = "SELECT page, oid FROM {$this->CONF['db_tbl_prefix']}questions WHERE qid = $dep_qid";

                                $rs = $this->db->Execute($check_query);
                                if($rs === FALSE)
                                { $error[] = 'Error checking dependencies: ' . $this->db->ErrorMsg(); }

                                while($r = $rs->FetchRow($rs))
                                {
                                    if($r['page'] > $page || ($r['page'] == $page && $r['oid'] > $oid))
                                    { $error[] = "Error: Dependencies can only be based on questions displayed BEFORE the question being added"; }
                                    elseif($r['page'] == $page)
                                    { $dep_require_pagebreak = 1; }
                                }

                                $option = $this->SfStr->getSafeString($option,SAFE_STRING_DB);

                                foreach($_REQUEST['dep_aid'][$num] as $dep_aid)
                                {
                                    $dep_id = $this->db->GenID($this->CONF['db_tbl_prefix'].'dependencies_sequence');
                                    $dep_insert .= "($dep_id,$sid,%%,$dep_qid," . (int)$dep_aid . ",$option), ";
                                }
                            }
                        }
                    }

                    //Add a Image to the question
					$qid = $this->db->GenID($this->CONF['db_tbl_prefix'].'questions_sequence');
					if (isset($_FILES['Imagen']) && !empty ($_FILES['Imagen']['name'])) 
					{		
						$size = getimagesize($_FILES['Imagen']['tmp_name']);
						if ($_FILES['Imagen']['size'] <= 20480 && $size['0'] <= IMAGE_ANCHO && $size['1'] <= IMAGE_ALTO)
						{
							$pos = strpos($_FILES['Imagen']['name'], '.');									
							$name_total = substr($_FILES['Imagen']['name'], 0, $pos);
							$extension = substr($_FILES['Imagen']['name'], $pos);
							if ($extension == '.gif' || $extension == '.jpg' || $extension == '.jpeg' || $extension == '.png'|| $extension == '.JPG' || $extension == '.JPEG' || $extension == '.PNG' || $extension == '.GIF') 
							{
								$file = $_FILES['Imagen']['tmp_name'];
								//$newfile = $_SERVER['DOCUMENT_ROOT'].'/'.NAMEAPP.'/html_image_q/'.$qid.$extension;
								$newfile = $_SERVER['DOCUMENT_ROOT'].PUBLICAPP.'/'.NAMEAPP.'/html_image_q/'.$qid.$extension;

								if (!copy($file, $newfile)) 
								{echo "failed to copy $file...\n";}
								$img_path = $qid.$extension;
							} 
							else
							{ $error[] = 'Image type not permmited. Please try another'; }
						}
						else
						{ $error[] = 'La imagen es muy grande. por favor cargue otra imagen'; }
					}
					
					//If no error has occurred, attempt to create new question in database
					
					if(empty($error))
					
                    {	//Insert question data into database
                       
                        $query = "INSERT INTO {$this->CONF['db_tbl_prefix']}questions (qid, sid, question, aid, num_answers, num_required, page, oid, orientation, img_path)
                                  VALUES ($qid, $sid, $question, $aid, $num_answers, $num_required, $page, $oid, $orientation, '$img_path')";
                        $rs = $this->db->Execute($query);
						
						if($rs === FALSE)
                        { $error[] = 'Error inserting new question: ' . $this->db->ErrorMsg(); }
                        else
                        {
							//Create dependencies in database and create page break, if required
                            if(!empty($dep_insert))
                            {
                                $dep_query = "INSERT INTO {$this->CONF['db_tbl_prefix']}dependencies (dep_id,sid,qid,dep_qid,dep_aid,dep_option) VALUES " . substr($dep_insert,0,-2);
                                $dep_query = str_replace('%%',$qid,$dep_query);

                                $rs = $this->db->Execute($dep_query);
                                if($rs === FALSE)
                                { $error[] = 'Error adding dependencies: ' . $this->db->ErrorMsg(); }

                                if($dep_require_pagebreak)
                                {
                                    $query = "UPDATE {$this->CONF['db_tbl_prefix']}questions SET page = page + 1 WHERE sid = $sid AND
                                              (page > $page OR (page = $page AND oid > $oid) OR qid = $qid)";
                                    $rs = $this->db->Execute($query);
                                    if($rs === FALSE)
                                    { $error[] = 'Cannot insert dependency page break: ' . $this->db->ErrorMsg(); }
                                }
                            }

                            $notice = 'Pregunta agregada exitosamente a la encuesta. a continuacion coloque respuestas';
                        }
                    }
                }
                else
                { $this->smarty->assign('question',$question); }
            }
        }

        //Set error or success message and redirect to appropriate page "AQUI LE PASO EL QID"
       
        $this->setMessageRedirect("add_answer.php?sid=$sid&qid=$qid&mode=questions&tipo={$this->data['tipo']}");
      

        if(empty($error))
        {
            if(empty($notice))
            { $notice = 'Question sucessfully added to survey.'; }
              
            $this->setMessage('&nbsp;',$notice,MSGTYPE_NOTICE);
        }
        else
        { 
        	$this->setMessageRedirect("question_edit_survey.php?sid=$sid&mode=questions");
		$this->setMessage('Error',implode('<br />',$error),MSGTYPE_ERROR); }
    }

    // LOAD EXISTING DATA FOR QUESTION BEING EDITED //
    function _loadEditQuestion($sid,$qid)
    {
        $sid = (int)$sid;
        $qid = (int)$qid;

        $error = array();

        $this->data['qid'] = $qid;
        $this->data['sid'] = $sid;

        //Retrieve Question data
        $query = "SELECT q.question, q.aid, q.num_answers, q.num_required, q.page, q.oid, q.orientation, s.survey_text_mode
                  FROM {$this->CONF['db_tbl_prefix']}questions q, {$this->CONF['db_tbl_prefix']}surveys s
                  WHERE q.sid = $sid AND q.sid = s.sid AND qid = $qid";
        $rs = $this->db->Execute($query);
        if($rs === FALSE)
        { $this->error('Error selecting data for question: ' . $this->db->ErrorMsg()); return; }

        $this->data['question_data'] = $rs->FetchRow($rs);
        $this->data['question_data']['question'] = $this->SfStr->getSafeString($this->data['question_data']['question'],SAFE_STRING_TEXT);

        $key = array_search($this->data['question_data']['orientation'],$this->CONF['orientation']);
        if($key !== FALSE)
        { $this->data['orientation']['selected'][$key] = ' selected'; }

        $this->data['num_answers'] = array("1","2","3","4","5");
        $this->data['num_answers_selected'] = array_fill(0,5,"");
        $this->data['num_answers_selected'][$this->data['question_data']['num_answers']-1] = " selected";

        $this->data['num_required'] = array("0","1","2","3","4","5");
        $this->data['num_required_selected'] = array_fill(0,6,"");
        $this->data['num_required_selected'][$this->data['question_data']['num_required']] = " selected";

        /*//Retrieve Answer Types from database
        $rs = $this->db->Execute("SELECT aid, name FROM {$this->CONF['db_tbl_prefix']}answer_types WHERE sid = $sid ORDER BY name ASC");
        if($rs === FALSE)
        { $this->error('Unable to retrieve answer types from database: ' . $this->db->ErrorMsg()); return; }

        while ($r = $rs->FetchRow($rs))
        {
            if($r['aid'] == $this->data['question_data']['aid'])
            { $r['selected'] = ' selected'; }
            $r['name'] = $this->SfStr->getSafeString($r['name'],SAFE_STRING_TEXT);
            $this->data['answer'][] = $r;
        }*/

        //Retrieve existing question numbers
        //for questions BEFORE this one being edited
        //and create Javascript for dependency <select> boxes
        $query = "SELECT q.qid, at.type, av.avid, av.value FROM {$this->CONF['db_tbl_prefix']}questions q,
                  {$this->CONF['db_tbl_prefix']}answer_types at LEFT JOIN {$this->CONF['db_tbl_prefix']}answer_values av
                  ON at.aid = av.aid WHERE q.sid = $sid AND
                  (q.page < {$this->data['question_data']['page']} OR (q.page = {$this->data['question_data']['page']} AND q.oid < {$this->data['question_data']['oid']}))
                  AND q.aid = at.aid ORDER BY page ASC, oid ASC";

        $x = 1;
        $av_count = 0;
        $old_qid = '';
        $this->data['js'] = '';
        $rs = $this->db->Execute($query);
        if($rs === FALSE)
        { $this->error('Error retrieving existing question numbers: ' . $this->db->ErrorMsg()); return;}
        if($r = $rs->FetchRow($rs))
        {
            do
            {
                if($r['type'] != ANSWER_TYPE_N)
                {
                    if($r['type'] == ANSWER_TYPE_S || $r['type'] == ANSWER_TYPE_T)
                    { $x++; }
                    else
                    {
                        if($r['qid'] != $old_qid)
                        {
                            if($av_count)
                            { $this->data['js'] .= "Num_Answers['{$old_qid}'] = '{$av_count}';\n"; }

                            $av_count = 0;
                            $this->data['qnum'][$r['qid']] = $x++;
                            $old_qid = $r['qid'];

                        }

                        $this->data['js'] .= "Answers['{$r['qid']},{$av_count}'] = '{$r['avid']}';\n";
                        $this->data['js'] .= "Values['{$r['qid']},{$av_count}'] = '" . addslashes($r['value']) . "';\n";

                        $av_count++;

                    }
                }
            }while($r = $rs->FetchRow($rs));

            $this->data['js'] .= "Num_Answers['{$old_qid}'] = '{$av_count}';\n";

            if(!empty($this->data['qnum']))
            {
                $this->data['dep_qid'] = array_keys($this->data['qnum']);
                $this->data['dep_qnum'] = array_values($this->data['qnum']);
            }
        }

        //Retrieve existing dependencies for question
        $this->data['dependencies'] = array();
        $query = "SELECT d.dep_id, d.dep_qid, d.dep_option, av.value FROM {$this->CONF['db_tbl_prefix']}dependencies d,
                  {$this->CONF['db_tbl_prefix']}answer_values av WHERE d.dep_aid = av.avid AND d.qid = $qid";
        $rs = $this->db->Execute($query);
        if($rs === FALSE)
        { $this->error('Unable to retrieve existing dependencies: ' . $this->db->ErrorMsg()); return; }

        while($r = $rs->FetchRow($rs))
        {
            $this->data['edep']['dep_id'][] = $r['dep_id'];
            $this->data['edep']['option'][] = $r['dep_option'];
            $this->data['edep']['qnum'][] = $this->data['qnum'][$r['dep_qid']];
            $this->data['edep']['value'][] = $this->SfStr->getSafeString($r['value'],$this->data['question_data']['survey_text_mode']);
        }
    }

}

?>